library(SPARK)
library(tidyverse)
library(Seurat)

get.gene_meta <- function(counts,locate,gene_features){
  gene_features$gene_id <- as.character(rownames(gene_features))
  gene_features$gene_name <- as.character(gene_features$feature_name)
  gene_features$counts <- as.vector(sp_sums_Rcpp(counts, rowSums=TRUE))
  gene_features$mean <- as.vector(sp_means_Rcpp(counts, rowMeans=TRUE))
  gene_features$var <- as.vector(sp_vars_Rcpp(counts, rowVars=TRUE))
  #gene_features$moransi <- RunMoransI(counts,locate)$observed
  return(gene_features)
}

call.sparkx <- function(counts,locate,gene_features){
  result <- sparkx(counts,locate,numCores=6,option="mixture")
  result <- result$res_mtest
  result$stat <- -log10(result$adjustedPval)
  
  result <- merge.data.frame(
    gene_features,result,
    by='row.names',all.y = T) |>
    #select("gene_id","gene_name","counts","mean","var","moransi","stat","combinedPval","adjustedPval")
    select("gene_id","gene_name","counts","mean","var","stat","combinedPval","adjustedPval")
  return(result)
}

rawdata <- readRDS("~/R_workspace/SVG/data/heart_hum_10x.rds")
rawdata <- readRDS("~/R_workspace/SVG/data/nose_10x.rds")
rawdata <- readRDS("~/R_workspace/SVG/data/kidney_10x.rds")
rawdata <- readRDS("~/R_workspace/SVG/data/HumanKidney_Puck_20011308.rds")
rawdata <- readRDS("~/R_workspace/SVG/data/Mouse_Puck_191112_05.rds")

counts <- rawdata@assays$RNA@data
locate <- rawdata@reductions[["spatial"]]@cell.embeddings
gene_features <- rawdata@assays[["RNA"]]@meta.features
gene_features <- get.gene_meta(counts,locate,gene_features)

result_count <- call.sparkx(counts,locate,gene_features)
result_count$dataset <- "kidney_mouse_slideseqv2"
result_count$preprocess <- "counts"

#total <- result_count
total <- rbind(total,result_count)
rm(result_count)

counts <- log1p(counts)
result_log <- call.sparkx(counts,locate,gene_features)
result_log$dataset <- "kidney_mouse_slideseqv2"
result_log$preprocess <- "log1p"
total <- rbind(total,result_log)
rm(result_log)
